<template>
	<div style="width: 100%;height: 100%;overflow: hidden;">
		<img src="../../static/image/cameraback.png" class="backimg" @click="back" />
		<video :width="width" :height="height" autoplay id="video" muted class="camera" v-if="!captureImage" playsinline> </video>
		<img src="../../static/image/camera.png" v-if="picType != 1 && picType != 2" class="loadimg" />
		<img src="../../static/image/camerazheng.png" v-if="picType == 1 && !captureImage" class="loadimg" />
		<img src="../../static/image/camerafan.png" v-if="picType == 2 && !captureImage" class="loadimg" />
		<div class="camera-content" v-if="cameraReady">
			<div class="op">
				<img src="../../static/image/switch.png" class="opimage" @click="switchCamera" v-show="!captureImage" />
				<img src="../../static/image/takephotobtn.png" class="opimage" @click="takePhoto" v-show="!captureImage"/>
				<img src="../../static/image/takephotobtn.png" class="opimage" @click="replaceTakePhoto" v-show="captureImage"/>
				<img src="../../static/image/sendpic.png" class="opimage" @click="sendpic" />
			</div>
			<img id="capture-image" :src="captureImage" v-show="captureImage" style="z-index: 2;"/>
			<!-- <canvas id="canvas" :width="width" :height="height" class="canvas" v-show="captureImage"></canvas> -->
			<!--选择摄像头-->
			<Modal v-model="showSelectCamera" :closable="false" :mask-closable="false">
				<p slot="header" style="height: 60px">
					<span style="color: #666666;font-size: 13px;height: 60px;white-space:pre-wrap;">{{ $t('camera.prompt') }}</span>
				</p>
				<RadioGroup v-model="selectCameraDeviceId" vertical>
					<Radio :label="device.deviceId" v-for="(device, index) in deviceVideoList" v-bind:key="device.deviceId">
						<Icon type="social-apple"></Icon>
						<span>{{ device.label }} {{ index + 1 }}</span>
					</Radio>
				</RadioGroup>
				<div slot="footer">
					<Button type="info" size="default" class="icbc_defaultbackColor" @click="selectCamera(selectCameraDeviceId)">{{ $t('ivcs.Yes') }}</Button>
				</div>
			</Modal>
		</div>
	</div>
</template>

<script>
import CoverVideo from './canvas';
import { stopTrack } from '../tool/tool';
export default {
	name: 'Camera',
	data() {
		return {
			videoStreamWidth: 0,
			videoStreamHeight: 0,
			width: window.screen.width, //document.body.clientWidth,//window.screen.width,
			height: window.screen.height, //document.body.clientHeight,//window.screen.height,
			cameraStream: null,
			deviceIds: [],
			deviceId: null,
			captureImage: null,
			showSelectCamera: false,
			selectCameraDeviceId: undefined,
			facingMode: 'environment',
			deviceVideoList: [],
			cameraReady: false,
			switchCameraIng: false,
			coverVideo: null,
			picType: localStorage.getItem('picType') // 1身份证正 2身份证反 3银行卡  4自拍照
		};
	},
	mounted() {
		this.initDevice();
	},
	methods: {
		/**
		 *  初始化video
		 * @param {*} video
		 */
		init (video) {
			this.coverVideo = new CoverVideo(video);
			console.log('CoverVideo', this.coverVideo);
		},

		/**
		 * 点击拍摄
		 */
		cameraImg (cb) {
			var video = document.getElementById('video');
			this.coverVideo.draw(video);
			setTimeout(() => {
				const image = this.coverVideo.canvas.toDataURL('image/png');
				cb(image);
				this.coverVideo = null;
			}, 100);
			this.coverVideo && this.coverVideo.closeView();
			this.width = window.screen.width;
			this.height = window.screen.height;
		},
		/*旋转照片*/
		rotateBase64Img(src, edg, callback) {
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var imgW; //图片宽度
			var imgH; //图片高度
			var size; //canvas初始大小
			if (edg % 90 != 0) {
				console.error('旋转角度必须是90的倍数!');
				throw '旋转角度必须是90的倍数!';
			}
			edg < 0 && (edg = (edg % 360) + 360);
			const quadrant = (edg / 90) % 4; //旋转象限
			const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; //裁剪坐标
			var image = new Image();
			image.crossOrigin = 'anonymous';
			image.src = src;
			image.onload = function() {
				imgW = image.width;
				imgH = image.height;
				size = imgW > imgH ? imgW : imgH;
				canvas.width = size * 2;
				canvas.height = size * 2;
				switch (quadrant) {
					case 0:
						cutCoor.sx = size;
						cutCoor.sy = size;
						cutCoor.ex = size + imgW;
						cutCoor.ey = size + imgH;
						break;
					case 1:
						cutCoor.sx = size - imgH;
						cutCoor.sy = size;
						cutCoor.ex = size;
						cutCoor.ey = size + imgW;
						break;
					case 2:
						cutCoor.sx = size - imgW;
						cutCoor.sy = size - imgH;
						cutCoor.ex = size;
						cutCoor.ey = size;
						break;
					case 3:
						cutCoor.sx = size;
						cutCoor.sy = size - imgW;
						cutCoor.ex = size + imgH;
						cutCoor.ey = size + imgW;
						break;
				}
				ctx.translate(size, size);
				ctx.rotate((edg * Math.PI) / 180);
				ctx.drawImage(image, 0, 0);
				var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
				if (quadrant % 2 == 0) {
					canvas.width = imgW;
					canvas.height = imgH;
				} else {
					canvas.width = imgH;
					canvas.height = imgW;
				}
				ctx.putImageData(imgData, 0, 0);
				callback(canvas.toDataURL());
			};
		},

		/**/
		initDevice() {
			this.captureImage = null;
			if (window.stream) {
				stopTrack(window.stream);
			}
			this.$Notice.info({
				title: 'Getting camera, please wait...',
				desc: '',
				duration: 2
			});
			navigator.mediaDevices
				.enumerateDevices()
				.then(this.getdevices)
				.then(this.getStream)
				.catch(this.handleError);
		},

		/*返回*/
		back() {
			if (this.cameraStream) {
				stopTrack(this.cameraStream);
			}
			this.$emit('back');
		},

		/*发送图片*/
		sendpic() {
			if (this.captureImage) {
				if (this.cameraStream) {
					stopTrack(this.cameraStream);
				}
				this.rotateBase64Img(this.captureImage, 270, (resp) => {
					this.$emit('sendPic', resp);
				});
				// this.$emit('sendPic', this.captureImage);
			} else {
				this.$Message.error('Please take photos first');
			}
		},

		switchCamera() {
			console.log('@@switchCamera');
			this.captureImage = null;
			this.coverVideo && this.coverVideo.closeView();
			this.coverVideo = null;
			if (!this.switchCameraIng) {
				this.switchCameraIng = true; //正在切换摄像头
				if (this.isAndroid()) {
					if (this.deviceIds.length > 1) {
						this.showSelectCamera = true;
					} else {
						this.switchCameraIng = false;
						this.$Message.info(this.$t('ivcs.onlyonecamera'));
					}
				} else if (this.isIos()) {
					if (this.facingMode === 'environment') {
						this.facingMode = 'user';
					} else {
						this.facingMode = 'environment';
					}
					this.getStream();
				}
			}
		},

		selectCamera(deviceId) {
			this.getStream(deviceId);
		},

		/**
		 * 重新拍照
		 */
		replaceTakePhoto(){
			if (this.captureImage) {
				this.captureImage = null;
				this.isTake = true;
			}
			this.getStream();
		},

		/*拍照*/
		takePhoto() {
			// if (this.captureImage) {
			// 	this.captureImage = null;
			// 	this.isTake = true;
			// 	// return;
			// }
			// var canvas = document.getElementById('canvas');
			// var context = canvas.getContext('2d');
			// var video = document.getElementById('video');
            // console.log('videoStreamWidth,,videoStreamHeight',this.videoStreamWidth,this.videoStreamHeight)
			// let ratio = this.videoStreamWidth / this.videoStreamHeight;
			// let drawWidth = canvas.width * ratio * 2;
			// // let drawHeight = drawWidth / ratio
			// let drawHeight = canvas.height * 1.1;
			// // 线上手机
			// this.videoStreamWidth < this.videoStreamHeight ? context.drawImage(video, 0, 0, drawWidth, drawHeight) : context.drawImage(video, -440, 0, drawWidth, drawHeight / 1.1);
			// var image = canvas.toDataURL('image/png');
			// var self = this;
			this.cameraImg((image)=>{
				// console.log(image);
				this.captureImage = image;
				// this.rotateBase64Img(image, 270, function(resp) {
				// 	self.captureImage = resp;
				// 	// console.log(resp);
				// 	self.isTake ? (self.isTake = false) : (self.isTake = true);
				// });
			});
	
		},

		getdevices(deviceInfos) {
			console.log('deviceInfos:', deviceInfos);
			for (var i = 0; i !== deviceInfos.length; i++) {
				let deviceInfo = deviceInfos[i];
				if (deviceInfo.kind === 'videoinput') {
					this.selectCameraDeviceId = deviceInfo.deviceId;
					this.deviceIds.push(deviceInfo.deviceId);
					this.deviceVideoList.push(deviceInfo);
				}
			}
		},

		//访问用户媒体设备的兼容方法
		getUserMedia(constrains, success, error) {
			if (navigator.mediaDevices.getUserMedia) {
				//最新标准API
				navigator.mediaDevices
					.getUserMedia(constrains)
					.then(success)
					.catch(error);
			} else if (navigator.webkitGetUserMedia) {
				//webkit内核浏览器
				navigator
					.webkitGetUserMedia(constrains)
					.then(success)
					.catch(error);
			} else if (navigator.mozGetUserMedia) {
				//Firefox浏览器
				navigator
					.mozGetUserMedia(constrains)
					.then(success)
					.catch(error);
			} else if (navigator.getUserMedia) {
				//旧版API
				navigator
					.getUserMedia(constrains)
					.then(success)
					.catch(error);
			}
		},

		/*获取媒体流*/
		getStream(/*deviceId*/) {
			if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
				this.width = window.screen.width;
				this.height = window.screen.height;
				//调用用户媒体设备，访问摄像头
				if (this.isIos()) {
					const constraints = {
						audio: true,
						video: {
							width: { ideal: 1920 }, //1280
							height: { ideal: 1080 }, //720
							frameRate: {
								ideal: 10,
								max: 15
							},
							facingMode: this.facingMode
							// deviceId: {exact: this.deviceId}
						}
					};
					if (this.cameraStream) {
						stopTrack(this.cameraStream);
					}
					console.log('stream options',constraints);
					this.getUserMedia(constraints, this.success, this.error);
				} else if (this.isAndroid()) {
					const constraints = {
						audio: true,
						video: {
							width: { ideal: 1280 },
							height: { ideal: 720 },
							frameRate: {
								ideal: 10,
								max: 15
							},
							deviceId: { exact: this.selectCameraDeviceId }
						}
					};
					this.getUserMedia(constraints, this.success, this.error);
				}
			} else {
				this.$Message.error('Your browser does not support access to user media devices');
			}
		},

		// 判断安卓
		isAndroid() {
			var u = navigator.userAgent;
			if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
				return true;
			}
			return false;
		},
		// 判断设备为 ios
		isIos() {
			var u = navigator.userAgent;
			if (u.indexOf('iPhone') > -1 || u.indexOf('iOS') > -1) {
				return true;
			}
			return false;
		},

		handleError(error) {
			this.showSelectCamera = false;
			console.log('error:', error);
			alert(error);
		},

		success(stream) {
			console.log('success',stream);
			var video = document.getElementById('video');
			//window.stream = stream;
			this.cameraStream = stream;
			this.width = window.screen.width;
			this.height = window.screen.height;
			//兼容webkit内核浏览器
			// var CompatibleURL = window.URL || window.webkitURL;
			//将视频流设置为video元素的源
			video.srcObject = stream;
			this.switchCameraIng = false;
			video.play();
			this.showSelectCamera = false;
			video.onloadstart = function(e) {
				console.log('onloadstart', e);
			};
			var self = this;
			video.addEventListener('canplay', function() {
				console.log(this.videoWidth, this.videoHeight);
				video.style.width = window.screen.width;
				video.style.height = window.screen.height;
				self.cameraReady = true;
			});
			video.onloadedmetadata = () => {
				video.play();
				this.init(video);
			};
		},

		error(error) {
			this.switchCameraIng = false;
			this.$Message.error(error.name + ':' + error.message);
			console.log(error, error.name, error.message);
			this.showSelectCamera = false;
		}
	}
};
</script>

<style scoped>
.loadimg {
	position: absolute;
	width: 80%;
	height: 80%;
	z-index: 2;
	top: 5%;
	left: 10%;
	object-fit: contain;
}

.camera {
	position: relative;
	z-index: 1;
	object-fit: cover;
	/* width: 100vw;
	height: 100vh; */
}

.canvas {
	z-index: 2;
	position: absolute;
	left: 0;
	top: 0;
	height: 100%;
	width: 100%;
	object-fit: fill;
	background-color: #999999;
}

.canvas:hover {
	object-fit: contain;
}

.op {
	position: absolute;
	width: 100%;
	height: 50px;
	bottom: 10px;
	left: 0px;
	/*background-color: yellow;*/
	z-index: 3;
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	align-items: center;
}

.backimg {
	position: absolute;
	left: 10px;
	top: 10px;
	z-index: 5;
	height: 50px;
	width: 50px;
}

.opimage {
	width: 50px;
	height: 50px;
}
</style>
